package com.bymboy.emos.wx.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bymboy.emos.wx.db.dao.TbDeptDao;
import com.bymboy.emos.wx.db.dao.TbUserDao;
import com.bymboy.emos.wx.db.pojo.MessageEntity;
import com.bymboy.emos.wx.db.pojo.TbUser;
import com.bymboy.emos.wx.exception.EmosException;
import com.bymboy.emos.wx.service.UserService;
import com.bymboy.emos.wx.task.MessageTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Package: com.bymboy.emos.wx.service.impl
 * @ClassName: UserServiceImpl
 * @Author: My
 * @CreateTime: 2021/9/23 8:53
 * @Description:
 */
@Service
@Slf4j
@Scope("prototype")
public class UserServiceImpl implements UserService {

    @Value("${wx.app-id}")
    private String appId;

    @Value("${wx.app-secret}")
    private String appSecret;

    @Resource
    private TbUserDao userDao;

    @Resource
    private TbDeptDao deptDao;

    @Autowired
    private MessageTask messageTask;

    private String getOpenId(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, Object> map = new HashMap<>();
        map.put("appid", appId);
        map.put("secret", appSecret);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String response = HttpUtil.post(url, map);
        JSONObject json = JSONUtil.parseObj(response);
        String openId = json.getStr("openid");
        if (openId == null && openId.length() == 0) {
            throw new RuntimeException("临时登录凭证错误");
        }
        return openId;
    }

    @Override
    public int registerUser(String registerCode, String code, String nickname, String photo) {
        //如果邀请码是000000，代表是超级管理员
        if (registerCode.equals("000000")) {
            //查询超级管理员账户是否已经绑定
            boolean bool = userDao.haveRootUserDao();
            if (!bool) {
                //把当前账户绑定到ROOT账户
                String openId = getOpenId(code);
                Map<String, Object> param = new HashMap<>();
                param.put("openId", openId);
                param.put("nickname", nickname);
                param.put("photo", photo);
                param.put("role", "[0]");
                param.put("status", 1);
                param.put("createTime", new Date());
                param.put("root", true);
                userDao.insert(param);
                Integer id = userDao.searchIdByOpenId(openId);

                MessageEntity entity = new MessageEntity();
                entity.setSenderId(0);
                entity.setSenderName("系统消息");
                entity.setUuid(IdUtil.simpleUUID());
                entity.setMsg("欢迎您注册成为超级管理员，请及时更新您的员工个人信息。");
                entity.setSendTime(new Date());
                messageTask.sendAsync(id + "", entity);

                return id;
            }
            //如果root已经绑定了，就抛出异常
            throw new EmosException("无法绑定超级管理员账号");
        } else {
            //其他用户

            return 0;
        }
    }

    @Override
    public Set<String> searchUserPermissions(int userId) {
        Set<String> permissions = userDao.searchUserPermissions(userId);
        return permissions;
    }

    @Override
    public Integer login(String code) {
        //根据临时授权字符串获取openId
        String openId = getOpenId(code);
        //判断该openId是否保存在数据库中
        Integer id = userDao.searchIdByOpenId(openId);
        if (id == null) {
            throw new EmosException("账户不存在");
        }

        //从消息队列中接收消息，转移到消息表
        //messageTask.receiveAysnc(id + "");

        return id;
    }

    @Override
    public TbUser searchById(int userId) {
        TbUser user = userDao.searchById(userId);
        return user;
    }

    @Override
    public String searchUserHiredate(int userId) {
        String hiredate = userDao.searchUserHiredate(userId);
        return hiredate;
    }

    @Override
    public HashMap searchUserSummary(int userId) {
        HashMap map = userDao.searchUserSummary(userId);
        return map;
    }

    @Override
    public ArrayList<HashMap<String, Object>> searchUserGroupByDept(String keyword) {
        ArrayList<HashMap<String, Object>> list_1 = deptDao.searchDeptMembers(keyword);
        ArrayList<HashMap<String, Object>> list_2 = userDao.searchUserGroupByDept(keyword);
        for (HashMap<String, Object> map_1 : list_1) {
            long id = (long) map_1.get("id");
            ArrayList<HashMap<String, Object>> members = new ArrayList<>();
            for (HashMap<String, Object> map_2 : list_2) {
                long deptId = (long) map_2.get("deptId");
                if (id == deptId) {
                    members.add(map_2);
                }
            }
            map_1.put("members", members);
        }
        return list_1;
    }

    @Override
    public ArrayList<HashMap<String, Object>> searchMembers(List param) {
        ArrayList<HashMap<String, Object>> list = userDao.searchMembers(param);
        return list;
    }
}
